package geoapi

import (
	"encoding/json"
	"errors"
	"strings"
)

type baiduResp struct {
	Status string
	Data   []struct {
		Location string
	}
}

// GeoBaidu 请求百度 api
// https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?
// resource_id=6006&ie=utf8&oe=utf8&format=json&query=xx.xx.xx.xx
func GeoBaidu(host string) (ig IPGeo, err error) {
	uri := `https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6006&ie=utf8&oe=utf8&format=json&query=` + host
	data, err := getApiData(uri)
	if err != nil {
		return
	}
	var t baiduResp
	err = json.Unmarshal(data, &t)
	if err != nil {
		return
	}
	if t.Status != "0" || len(t.Data) == 0 {
		err = errors.New("parameter error")
		return
	}
	ig.Location = t.Data[0].Location
	l := strings.Split(ig.Location, " ")
	if len(l) == 2 {
		ig.Location = l[0]
		ig.Isp = l[1]
	} else if len(l) > 2 {
		ig.Location = l[0]
		ig.Isp = l[len(l)-1]
	}
	ig.CountryCode = getCountryCode(ig.Location)
	ig.Query = host
	ig.Status = "success"
	return
}
